package com.corticon.dialogs.util;

import java.text.DecimalFormat;

/**
 *
 * @author Lifan Yang
 * @since 2008-10-20
 */
public class QuestionUtils {

    public static final String QUESTION_REFID_PREFIX = "Q-";
    public static final String PAGE_REFID_PREFIX = "P-";
    public static final String DIALOG_REFID_PREFIX = "D-";
    public static final String REFID_BEGIN = "00001";
    private static final DecimalFormat REF_ID_FORMAT = new DecimalFormat("00000");

    public static String getNextRefId(String maxRefId) {

        // Get the prefix of the refId, like Q -> Question, P -> Page.
        // TODO: static
        String prefix = maxRefId.substring(0, 2);
        // Get the number part of the refId.
        String refIdString = maxRefId.substring(2);

        int nextRefId = Integer.parseInt(refIdString) + 1;

        return prefix + REF_ID_FORMAT.format(nextRefId);
    }

    /**
     * This method is used to get the priority value according to the sequence value. For example,
     * if the sequence value is 1.1.1.1, the corresponding priority value is 1.111
     *
     * This method is used by postQuestions and previewOnEdit methods.
     *
     * @param sequence
     * @return
     */
    public static Double calculatePriority(String sequence) {
        String root = sequence.substring(0, sequence.indexOf(".") + 1);
        String sub = sequence.substring(sequence.indexOf(".") + 1, sequence.length()).replace(".",
            "");
        return Double.valueOf(root + sub);
    }

     /**
     * This method is used to compare the sequence in question For example,
     * 1.1 and 1.1.1, the order should be 1.1, 1.1.1.
     * @param smallerSequence, biggerSequence
     * @return
     */
    public static int compareSequence(String smallerSequence, String biggerSequence) {
        int i = 0;
        String[] sequence1 = smallerSequence.split("\\.");
        String[] sequence2 = biggerSequence.split("\\.");
        int count1 = sequence1.length;
        int count2 = sequence2.length;
        int count = count1 > count2 ? count2 : count1;
        int result = 0;
        while (i < count) {
            int s1 = Integer.parseInt(sequence1[i]);
            int s2 = Integer.parseInt(sequence2[i]);
            if (s1 != s2) {
                result = s1 - s2;
                break;
            } else {
                if (i == count-1) {
                    result = count1 - count2;
                }
            }
            i++;
        }
        return result;
    }

}
